package org.csu.onlineedubackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.csu.onlineedubackend.dto.*;
import org.csu.onlineedubackend.entity.Survey;
import org.csu.onlineedubackend.entity.SurveyQuestion;
import org.csu.onlineedubackend.entity.SurveyOption;
import org.csu.onlineedubackend.entity.SurveyAnswer;
import org.csu.onlineedubackend.mapper.SurveyMapper;
import org.csu.onlineedubackend.mapper.SurveyQuestionMapper;
import org.csu.onlineedubackend.mapper.SurveyOptionMapper;
import org.csu.onlineedubackend.mapper.SurveyAnswerMapper;
import org.csu.onlineedubackend.service.SurveyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SurveyServiceImpl extends ServiceImpl<SurveyMapper, Survey> implements SurveyService {

    @Autowired
    private SurveyQuestionMapper surveyQuestionMapper;
    
    @Autowired
    private SurveyOptionMapper surveyOptionMapper;
    
    @Autowired
    private SurveyAnswerMapper surveyAnswerMapper;

    @Override
    @Transactional
    public Integer createSurvey(CreateSurveyDTO createSurveyDTO) {
        // 1. 创建问卷
        Survey survey = new Survey();
        survey.setTitle(createSurveyDTO.getTitle());
        survey.setDescription(createSurveyDTO.getDescription());
        survey.setTargetRole(createSurveyDTO.getTargetRole());
        
        this.save(survey);
        
        // 2. 创建题目和选项
        if (createSurveyDTO.getQuestions() != null) {
            for (int i = 0; i < createSurveyDTO.getQuestions().size(); i++) {
                CreateSurveyQuestionDTO questionDTO = createSurveyDTO.getQuestions().get(i);
                
                SurveyQuestion question = new SurveyQuestion();
                question.setSurveyId(survey.getId());
                question.setQuestionText(questionDTO.getQuestionText());
                question.setQuestionType(questionDTO.getQuestionType());
                question.setSortOrder(i + 1);
                
                surveyQuestionMapper.insert(question);
                
                // 3. 创建选项（如果有的话）
                if (questionDTO.getOptions() != null && !questionDTO.getOptions().isEmpty()) {
                    for (int j = 0; j < questionDTO.getOptions().size(); j++) {
                        SurveyOption option = new SurveyOption();
                        option.setQuestionId(question.getId());
                        option.setOptionText(questionDTO.getOptions().get(j));
                        option.setSortOrder(j + 1);
                        
                        surveyOptionMapper.insert(option);
                    }
                }
            }
        }
        
        return survey.getId();
    }

    @Override
    public SurveyDTO getSurveyDetail(Integer surveyId) {
        // 1. 获取问卷基本信息
        Survey survey = this.getById(surveyId);
        if (survey == null) {
            return null;
        }
        
        SurveyDTO surveyDTO = new SurveyDTO();
        surveyDTO.setId(survey.getId());
        surveyDTO.setTitle(survey.getTitle());
        surveyDTO.setDescription(survey.getDescription());
        surveyDTO.setTargetRole(survey.getTargetRole());
        surveyDTO.setCreatedAt(survey.getCreatedAt());
        surveyDTO.setParticipantCount(baseMapper.getParticipantCount(surveyId));
        
        // 2. 获取题目列表
        QueryWrapper<SurveyQuestion> questionWrapper = new QueryWrapper<>();
        questionWrapper.eq("survey_id", surveyId).orderByAsc("sort_order");
        List<SurveyQuestion> questions = surveyQuestionMapper.selectList(questionWrapper);
        
        List<SurveyQuestionDTO> questionDTOs = new ArrayList<>();
        for (SurveyQuestion question : questions) {
            SurveyQuestionDTO questionDTO = new SurveyQuestionDTO();
            questionDTO.setId(question.getId());
            questionDTO.setSurveyId(question.getSurveyId());
            questionDTO.setQuestionText(question.getQuestionText());
            questionDTO.setQuestionType(question.getQuestionType());
            questionDTO.setSortOrder(question.getSortOrder());
            
            // 3. 获取选项列表
            QueryWrapper<SurveyOption> optionWrapper = new QueryWrapper<>();
            optionWrapper.eq("question_id", question.getId()).orderByAsc("sort_order");
            List<SurveyOption> options = surveyOptionMapper.selectList(optionWrapper);
            
            List<SurveyOptionDTO> optionDTOs = options.stream().map(option -> {
                SurveyOptionDTO optionDTO = new SurveyOptionDTO();
                optionDTO.setId(option.getId());
                optionDTO.setQuestionId(option.getQuestionId());
                optionDTO.setOptionText(option.getOptionText());
                optionDTO.setSortOrder(option.getSortOrder());
                return optionDTO;
            }).collect(Collectors.toList());
            
            questionDTO.setOptions(optionDTOs);
            questionDTOs.add(questionDTO);
        }
        
        surveyDTO.setQuestions(questionDTOs);
        return surveyDTO;
    }

    @Override
    public PageResponseDTO<SurveyDTO> getSurveyPage(int page, int size) {
        Page<Survey> pageParam = new Page<>(page, size);
        QueryWrapper<Survey> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("created_at");
        
        IPage<Survey> surveyPage = this.page(pageParam, queryWrapper);
        
        List<SurveyDTO> surveyDTOs = surveyPage.getRecords().stream().map(survey -> {
            SurveyDTO surveyDTO = new SurveyDTO();
            surveyDTO.setId(survey.getId());
            surveyDTO.setTitle(survey.getTitle());
            surveyDTO.setDescription(survey.getDescription());
            surveyDTO.setTargetRole(survey.getTargetRole());
            surveyDTO.setCreatedAt(survey.getCreatedAt());
            surveyDTO.setParticipantCount(baseMapper.getParticipantCount(survey.getId()));
            return surveyDTO;
        }).collect(Collectors.toList());
        
        return new PageResponseDTO<>(surveyDTOs, surveyPage.getTotal(), surveyPage.getSize(), surveyPage.getCurrent());
    }

    @Override
    @Transactional
    public boolean deleteSurvey(Integer surveyId) {
        // 删除问卷会级联删除题目、选项和答案
        return this.removeById(surveyId);
    }

    @Override
    @Transactional
    public boolean submitSurveyAnswer(Integer surveyId, Integer userId, List<SurveyAnswerDTO> answers) {
//        System.out.println("s" +surveyId + ";" + "u" + userId + ";");
        // 检查是否已经提交过
        QueryWrapper<SurveyAnswer> checkWrapper = new QueryWrapper<>();
        checkWrapper.eq("survey_id", surveyId).eq("user_id", userId);
        if (surveyAnswerMapper.selectCount(checkWrapper) > 0) {
            return false; // 已经提交过了
        }
        
        // 批量插入答案
        for (SurveyAnswerDTO answerDTO : answers) {
            SurveyAnswer answer = new SurveyAnswer();
            answer.setSurveyId(surveyId);
            answer.setQuestionId(answerDTO.getQuestionId());
            answer.setUserId(userId);
            answer.setAnswerText(answerDTO.getAnswerText());
            
            surveyAnswerMapper.insert(answer);
        }
        
        return true;
    }

    @Override
    public Map<String, Object> getSurveyStatistics(Integer surveyId) {
        Map<String, Object> statistics = new HashMap<>();
        
        // 1. 获取问卷基本信息
        SurveyDTO survey = getSurveyDetail(surveyId);
        statistics.put("survey", survey);
        
        // 2. 获取参与人数
        Integer participantCount = baseMapper.getParticipantCount(surveyId);
        statistics.put("participantCount", participantCount);
        
        // 3. 获取每道题的统计
        List<Map<String, Object>> questionStats = new ArrayList<>();
        if (survey != null && survey.getQuestions() != null) {
            for (SurveyQuestionDTO question : survey.getQuestions()) {
                Map<String, Object> questionStat = new HashMap<>();
                questionStat.put("questionId", question.getId());
                questionStat.put("questionText", question.getQuestionText());
                questionStat.put("questionType", question.getQuestionType());
                
                // 获取该题的所有答案
                QueryWrapper<SurveyAnswer> answerWrapper = new QueryWrapper<>();
                answerWrapper.eq("question_id", question.getId());
                List<SurveyAnswer> answers = surveyAnswerMapper.selectList(answerWrapper);
                
                if ("single".equals(question.getQuestionType()) ||
                    "multiple".equals(question.getQuestionType())) {
                    // 选择题统计
                    Map<String, Integer> optionCounts = new HashMap<>();
                    for (SurveyAnswer answer : answers) {
                        String[] selectedOptions = answer.getAnswerText().split(",");
                        for (String option : selectedOptions) {
                            optionCounts.put(option.trim(), optionCounts.getOrDefault(option.trim(), 0) + 1);
                        }
                    }
                    questionStat.put("optionCounts", optionCounts);
                } else if ("rating".equals(question.getQuestionType())) {
                    // 评分题统计
                    List<Integer> ratings = answers.stream()
                        .map(answer -> Integer.parseInt(answer.getAnswerText()))
                        .collect(Collectors.toList());
                    
                    double averageRating = ratings.stream().mapToInt(Integer::intValue).average().orElse(0.0);
                    questionStat.put("averageRating", averageRating);
                    questionStat.put("totalRatings", ratings.size());  // 回答人数
                } else {
                    // 文本题统计
                    questionStat.put("answerCount", answers.size());
                    List<String> texts = answers.stream()
                            .map(SurveyAnswer::getAnswerText)
                            .filter(text -> text != null && !text.trim().isEmpty())
                            .collect(Collectors.toList());
                    questionStat.put("answerTexts", texts);  // 回答的具体内容
                }
                
                questionStats.add(questionStat);
            }
        }
        
        statistics.put("questionStats", questionStats);
        return statistics;
    }

    @Override
    public List<SurveyDTO> getAvailableSurveys(Integer userId, Integer userRole) {
        QueryWrapper<Survey> queryWrapper = new QueryWrapper<>();
        
        // 根据用户角色过滤问卷
        if (userRole == 1) { // 学生
            queryWrapper.in("target_role", 1, 3); // 学生或全部
        } else if (userRole == 2) { // 老师
            queryWrapper.in("target_role", 2, 3); // 老师或全部
        }
        
        queryWrapper.orderByDesc("created_at");
        List<Survey> surveys = this.list(queryWrapper);
        
        return surveys.stream().map(survey -> {
            SurveyDTO surveyDTO = new SurveyDTO();
            surveyDTO.setId(survey.getId());
            surveyDTO.setTitle(survey.getTitle());
            surveyDTO.setDescription(survey.getDescription());
            surveyDTO.setTargetRole(survey.getTargetRole());
            surveyDTO.setCreatedAt(survey.getCreatedAt());
            surveyDTO.setParticipantCount(baseMapper.getParticipantCount(survey.getId()));
            return surveyDTO;
        }).collect(Collectors.toList());
    }
} 